#pragma once
#include <string>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdarg>
#include <unistd.h>
#include "error.hpp"

enum
{
    Debug = 1,
    Info,
    Warning,
    Error,
    Fatal,
    Unknown
};
const char *filenameBase = "log/log";

std::string getLevel(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Unknown";
    }
}

std::string getTime()
{
    time_t now = time(nullptr);
    struct tm *t = localtime(&now);
    char buffer[1024]{0};
    snprintf(buffer, sizeof(buffer) - 1, "%d-%d-%d %d:%d:%d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
             t->tm_hour, t->tm_min, t->tm_sec);
    return buffer;
}

void logMessage(int level, const char *format, ...)
{
    char bufferLeft[1024]{0};
    std::string logLevel = getLevel(level);
    std::string curTime = getTime();
    snprintf(bufferLeft, sizeof(bufferLeft) - 1, "[%s] [%s] %d :", curTime.c_str(), logLevel.c_str(), getpid());
    
    char bufferRight[1024]{0};
    va_list args;
    va_start(args, format);
    vsnprintf(bufferRight, sizeof(bufferRight) - 1, format, args);
    va_end(args);

    std::string logMessage = bufferLeft + std::string(bufferRight) + "\n";
    std::string filename = std::string(filenameBase) + logLevel + std::string(".log");
    // C语言版本的文件操作
    FILE *fp = fopen(filename.c_str(), "a");
    if (fp == nullptr)
    {
        perror("fopen");
        return;
    }
    fwrite(logMessage.c_str(), logMessage.size(), sizeof(char), fp);
    fclose(fp);
    // C++版本的文件操作 TODO
}